import pandas as pd
import numpy as np
import geopandas as gpd
import folium
from datetime import datetime
import mglearn
from tqdm import tqdm
from pandas import DataFrame
import matplotlib.pyplot as plt
import folium
plt.rc('font', family='Malgun Gothic')
교통사고내역 = pd.read_csv('1.대전광역시_교통사고내역(2017~2019).csv')
교통사고격자 = gpd.read_file('2.대전광역시_교통사고격자(2017~2019).geojson')
# 교통안전시설물 data loading
교통사고격자 = gpd.read_file('2.대전광역시_교통사고격자(2017~2019).geojson')
신호등_보행등 = gpd.read_file("3.대전광역시_신호등(보행등).geojson")
신호등_차량등 = gpd.read_file("4.대전광역시_신호등(차량등).geojson")
안전지대 = gpd.read_file("5.대전광역시_안전지대.geojson")
횡단보도 = gpd.read_file("6.대전광역시_횡단보도.geojson")
도로속도표시 = gpd.read_file("7.대전광역시_도로속도표시.geojson")
정차금지지대 = gpd.read_file("8.대전광역시_정차금지지대.geojson")
교통안전표지 = gpd.read_file("9.대전광역시_교통안전표지.geojson")
교통CCTV = gpd.read_file("10.대전광역시_교통CCTV.geojson")
중앙분리대 = gpd.read_file("31.대전시_중앙분리대.geojson")
동별_인구현황 = pd.read_csv('11.대전광역시_동별_인구현황(2017~2019).csv')
인구정보_총인구 = gpd.read_file('12.대전광역시_인구정보(총인구).geojson')
인구정보_고령 = gpd.read_file('13.대전광역시_인구정보(고령).geojson')
인구정보_생산가능 = gpd.read_file('14.대전광역시_인구정보(생산가능).geojson')
인구정보_유소년 = gpd.read_file('15.대전광역시_인구정보(유소년).geojson')
기상데이터 = pd.read_csv('16.대전광역시_기상데이터(2017~2019).csv')
차량등록현황 = gpd.read_file('30.대전광역시_차량등록현황_격자.geojson')
도로명주소_건물 = gpd.read_file('23.대전광역시_도로명주소(건물).geojson')
평일_일별_혼잡빈도강도 = pd.read_csv("21.대전광역시_평일_일별_혼잡빈도강도(2018).csv")
평일_일별_시간대별_추정교통량 = pd.read_csv("20.대전광역시_평일_일별_시간대별_추정교통량(2018).csv")
교통사고내역 = pd.read_csv('1.대전광역시_교통사고내역(2017~2019).csv')
교통사고내역.head()
aa = 교통사고내역.loc[교통사고내역['피해운전자 연령대'] == '10대미만'].groupby(['시군구'])[['gid']].count().sort_values(by='gid', ascending=False)[:10]
pd.set_option('display.max_rows', aa.shape[0]+1)
aa
bb = 교통사고내역.loc[교통사고내역['피해운전자 연령대'] == '10대'].groupby(['시군구'])[['gid']].count().sort_values(by='gid', ascending=False)
pd.set_option('display.max_rows', bb.shape[0]+1)
bb
bb = 교통사고내역.loc[(교통사고내역['피해운전자 연령대'] == '10대') | (교통사고내역['피해운전자 연령대'] == '20대')
| (교통사고내역['피해운전자 연령대'] == '30대') | (교통사고내역['피해운전자 연령대'] == '40대') | (교통사고내역['피해운전자 연령대'] == '50대')].groupby(['시군구'])[['gid']].count().sort_values(by='gid', ascending=False)[:10]
pd.set_option('display.max_rows', bb.shape[0]+1)
bb
cc = 교통사고내역.loc[(교통사고내역['피해운전자 연령대'] == '50대') | (교통사고내역['피해운전자 연령대'] == '60대')
| (교통사고내역['피해운전자 연령대'] == '70대') | (교통사고내역['피해운전자 연령대'] == '80대') | (교통사고내역['피해운전자 연령대'] == '90대')].groupby(['시군구'])[['gid']].count().sort_values(by='gid', ascending=False)[:10]
pd.set_option('display.max_rows', cc.shape[0]+1)
cc
교통사고내역['사고일'] = 교통사고내역['사고일'].map(lambda x : datetime.strptime(str(x), '%Y-%m-%d'))
교통사고내역['year'] = 교통사고내역['사고일'].map(lambda x : x.strftime('%Y'))
교통사고내역['month'] = 교통사고내역['사고일'].map(lambda x : x.strftime('%m'))
교통사고내역['day'] = 교통사고내역['사고일'].map(lambda x : x.strftime('%d'))
교통사고내역['사고'] = 교통사고내역['사고유형'].str.split('-').str[0].str.strip()
교통사고내역['유형'] = 교통사고내역['사고유형'].str.split('-').str[1].str.strip()
교통사고내역['구'] = 교통사고내역['시군구'].str.split(' ').str[1]
교통사고내역['동'] = 교통사고내역['시군구'].str.split(' ').str[2]
traffic = pd.merge(교통사고내역,교통사고격자, on='gid')
traffic
# 결측치 확인
교통사고내역.isnull().sum()
# 피해자운전자 정보가 없는 671건 모두 차량단독 사고
교통사고내역[(교통사고내역['피해운전자 차종'].isnull()) & (교통사고내역['사고'] != '차량단독')]
# 이상치 확인
교통사고내역['가해운전자 연령대'].unique()
교통사고내역['피해운전자 연령대'].unique()
교통사고내역['가해운전자 차종'].unique()
교통사고내역['사망자수'].unique()
교통사고내역['중상자수'].unique()
교통사고내역.loc[교통사고내역['중상자수']==16, ['가해운전자 차종','피해운전자 차종']]
교통사고내역['경상자수'].unique()
교통사고내역.loc[교통사고내역['경상자수'] ==19, ['가해운전자 차종','피해운전자 차종']]
교통사고내역['부상신고자수'].unique()
교통사고내역.loc[교통사고내역['부상신고자수'] ==12]
# 2017-2019 사고 수
v1 = traffic.groupby(['year'])[['acci_cnt']].count()
v1.head()
plt.plot(v1, marker='o')
plt.xlabel('사고연도') # x축 이름
plt.ylabel('발생사고수') # y축 이름
plt.ylim([7000,9000]) # y축 범위
plt.title('대전시 교통사고 발생건수')
mm = traffic.groupby(['year'])[['사망자수', '중상자수', '경상자수']].sum()
mm.reset_index(inplace=True)
mm.head()
mmm = mm.T
mmm.reset_index(inplace=True)
mmm.head()
x = np.arange(len(mmm['index'])) # the label locations
width = 0.25 # the width of the bars
fig, ax = plt.subplots()
rects1 = ax.bar(x, mmm['2017'], width, label='2017', color='#9acfff')
rects2 = ax.bar(x + width, mmm['2018'], width, label='2018', color='#a89aff')
rects3 = ax.bar(x + width + width, mmm['2019'], width, label='2019', color='#EE3224')
# Add some text for labels, title and custom x-axis tick labels, etc.
ax.set_ylabel('수')
ax.set_title('대전시 교통사고')
# ax.set_xticks(x)
ax.set_xticklabels(mmm['index'])
ax.set_xticks(x + width / 2)
ax.legend()
for bar in ax.patches:
bar_value = bar.get_height()
# Format the text with commas to separate thousands. You can do
# any type of formatting here though.
text = f'{bar_value:,}'
# This will give the middle of each bar on the x-axis.
text_x = bar.get_x() + bar.get_width() / 2
# get_y() is where the bar starts so we add the height to it.
text_y = bar.get_y() + bar_value
# If we want the text to be the same color as the bar, we can
# get the color like so:
bar_color = bar.get_facecolor()
# If you want a consistent color, you can just set it as a constant, e.g. #222222
ax.text(text_x, text_y, text, ha='center', va='bottom', color=bar_color,
size=10)
# Setting the x-axis and y-axis limits
plt.xlim(min(x)-width, max(x)+width*4)
plt.ylim([0, max(1000 + mmm['2019'])] )
fig.tight_layout()
plt.show()
# 2017 ~ 2019 사고
acci_100 = traffic.groupby(['동'])[['acci_cnt']].count().sort_values(by='acci_cnt', ascending=False)[:100]
pd.set_option('display.max_rows', acci_100.shape[0]+1)
acci_100
acci_20 = acci_100[:20]
acci_20
from matplotlib.ticker import StrMethodFormatter
ax = acci_20.plot(kind='barh', figsize=(8, 10), color='#86bf91', zorder=2, width=0.85)
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.spines['left'].set_visible(False)
ax.spines['bottom'].set_visible(False)
# Switch off ticks
ax.tick_params(axis="both", which="both", bottom="off", top="off", labelbottom="on", left="off", right="off", labelleft="on")
# Draw vertical axis lines
vals = ax.get_xticks()
for tick in vals:
ax.axvline(x=tick, linestyle='dashed', alpha=0.4, color='#eeeeee', zorder=1)
# Set x-axis label
ax.set_xlabel("사고 발생건수", labelpad=20, weight='bold', size=12)
# Set y-axis label
ax.set_ylabel('Top20 동이름', labelpad=20, weight='bold', size=12)
# Format y-axis label
ax.xaxis.set_major_formatter(StrMethodFormatter('{x:,g}'))
ax.invert_yaxis()
acc_2 = traffic.groupby(['year','동'])[['acci_cnt']].sum()
pd.set_option('display.max_rows', acc_2.shape[0]+1)
acc_2
n1 = traffic.groupby(['year','사고'])[['acci_cnt']].count()
n1.reset_index(inplace=True)
n11 = n1.pivot_table(index='사고', columns = 'year', values='acci_cnt')
n11.reset_index(inplace=True)
n11 = n11.T
n11.columns = n11.iloc[0,:]
n11
c2c = traffic.loc[traffic['사고']=='차대차'].groupby(['동'])[['acci_cnt']].sum().sort_values(by='acci_cnt',ascending=False)[:100]
c2p = traffic.loc[traffic['사고']=='차대사람'].groupby(['동'])[['acci_cnt']].sum().sort_values(by='acci_cnt',ascending=False)[:100]
c2 = traffic.loc[traffic['사고']=='차량단독'].groupby(['동'])[['acci_cnt']].sum().sort_values(by='acci_cnt',ascending=False)[:100]
a1 = np.intersect1d(np.array(c2c.index),np.array(c2p.index))
a2 = np.intersect1d(np.array(c2c.index),np.array(c2.index))
a3 = np.intersect1d(np.array(c2p.index),np.array(c2.index))
c2c_c2p = pd.merge(c2c, c2p, on='동', how = 'outer')
c2c_c2p_c2 = pd.merge(c2c_c2p, c2, on='동', how = 'outer')
c2c_c2p_c2.columns = ['차대차', '차대사람', '차량단독']
c2c_c2p_c2 = pd.merge(acci_100, c2c_c2p_c2, on='동', how = 'outer')
c2c_c2p_c2_rank = c2c_c2p_c2.rank(ascending=False)
pd.set_option('display.max_rows', c2c_c2p_c2_rank.shape[0]+1)
c2c_c2p_c2_rank
# 격자 데이터
data_gid = 교통사고격자[['gid', 'geometry']]
차량등록현황.head()
차량등록현황 = 차량등록현황[['gid', 'cars_cnt']]
인구정보_총인구.head()
인구정보_총인구 = 인구정보_총인구.rename({'val':'pop_cnt'},axis=1)
인구정보_총인구 = 인구정보_총인구[['gid', 'pop_cnt']]
인구정보_고령.head()
인구정보_고령 = 인구정보_고령.rename({'val':'pop_old_cnt'},axis=1)
인구정보_고령 = 인구정보_고령[['gid', 'pop_old_cnt']]
인구정보_생산가능.head()
인구정보_생산가능 = 인구정보_생산가능.rename({'val':'pop_mid_cnt'},axis=1)
인구정보_생산가능 = 인구정보_생산가능[['gid', 'pop_mid_cnt']]
인구정보_유소년.head()
인구정보_유소년 = 인구정보_유소년.rename({'val':'pop_young_cnt'},axis=1)
인구정보_유소년 = 인구정보_유소년[['gid', 'pop_young_cnt']]
신호등_보행등 = gpd.read_file("3.대전광역시_신호등(보행등).geojson")
신호등_보행등.head()
gid_list = []
for i in tqdm(range(신호등_보행등.shape[0])):
point = 신호등_보행등['geometry'].iloc[i]
if data_gid['geometry'].contains(point).sum() == 0:
g1 = "Na"
else :
g = data_gid['gid'].loc[data_gid['geometry'].contains(point)]
g1 = g.iloc[0]
gid_list.append(g1)
신호등_보행등['gid'] = gid_list
신호등_보행등['gid'] = gid_list
신호등_보행등['PTL_cnt']=1
result_cnt = 신호등_보행등.groupby(['gid']).sum()
result_cnt.reset_index(inplace=True)
신호등_보행등 = result_cnt
신호등_보행등 = 신호등_보행등[['gid', 'PTL_cnt']]
신호등_보행등.to_csv('신호등_보행등.csv')
신호등_차량등.head()
gid_list = []
for i in tqdm(range(신호등_차량등.shape[0])):
point = 신호등_차량등['geometry'].iloc[i]
if data_gid['geometry'].contains(point).sum() == 0:
g1 = "Na"
else :
g = data_gid['gid'].loc[data_gid['geometry'].contains(point)]
g1 = g.iloc[0]
gid_list.append(g1)
신호등_차량등['gid'] = gid_list
신호등_차량등['CTL_cnt']=1
result_cnt = 신호등_차량등.groupby(['gid']).sum()
result_cnt.reset_index(inplace=True)
신호등_차량등 = result_cnt
신호등_차량등 = 신호등_차량등[['gid', 'CTL_cnt']]
신호등_차량등.to_csv('신호등_차량등.csv')
gid_list = []
for i in tqdm(range(안전지대.shape[0])):
point = 안전지대['geometry'].iloc[i]
if data_gid['geometry'].contains(point).sum() == 0:
g1 = "Na"
else :
g = data_gid['gid'].loc[data_gid['geometry'].contains(point)]
g1 = g.iloc[0]
gid_list.append(g1)
안전지대['gid'] = gid_list
안전지대['SafeZone_cnt']=1
result_cnt = 안전지대.groupby(['gid']).sum()
result_cnt.reset_index(inplace=True)
안전지대 = result_cnt
안전지대 = 안전지대[['gid', 'SafeZone_cnt']]
안전지대.to_csv('안전지대.csv')
횡단보도
횡단보도.head()
gid_list = []
for i in tqdm(range(횡단보도.shape[0])):
point = 횡단보도['geometry'].iloc[i]
if data_gid['geometry'].contains(point).sum() == 0:
g1 = "Na"
else :
g = data_gid['gid'].loc[data_gid['geometry'].contains(point)]
g1 = g.iloc[0]
gid_list.append(g1)
횡단보도['gid'] = gid_list
횡단보도['Pedcrossing_cnt']=1
result_cnt = 횡단보도.groupby(['gid']).sum()
result_cnt.reset_index(inplace=True)
횡단보도 = result_cnt
횡단보도 = 횡단보도[['gid', 'Pedcrossing_cnt']]
횡단보도.to_csv('횡단보도.csv')
도로속도표시 = gpd.read_file("7.대전광역시_도로속도표시.geojson")
도로속도표시.head()
gid_list = []
for i in tqdm(range(도로속도표시.shape[0])):
point = 도로속도표시['geometry'].iloc[i]
if data_gid['geometry'].contains(point).sum() == 0:
g1 = "NA"
else :
g = data_gid['gid'].loc[data_gid['geometry'].contains(point)]
g1 = g.iloc[0]
gid_list.append(g1)
도로속도표시['gid'] = gid_list
도로속도표시['speed_cnt']=1
result_cnt = 도로속도표시.groupby(['gid']).sum()
result_cnt.reset_index(inplace=True)
도로속도표시 = result_cnt
도로속도표시 = 도로속도표시[['gid', 'speed_cnt']]
도로속도표시.to_csv('도로속도표시.csv')
도로속도표시
정차금지지대.head()
gid_list = []
for i in tqdm(range(정차금지지대.shape[0])):
point = 정차금지지대['geometry'].iloc[i]
if data_gid['geometry'].contains(point).sum() == 0:
g1 = "NA"
else :
g = data_gid['gid'].loc[data_gid['geometry'].contains(point)]
g1 = g.iloc[0]
gid_list.append(g1)
정차금지지대['gid'] = gid_list
정차금지지대['nostop_cnt']=1
result_cnt = 정차금지지대.groupby(['gid']).sum()
result_cnt.reset_index(inplace=True)
정차금지지대 = result_cnt
정차금지지대 = 정차금지지대[['gid', 'nostop_cnt']]
정차금지지대.head()
정차금지지대.to_csv('정차금지지대.csv')
교통안전표지.head()
gid_list = []
for i in tqdm(range(교통안전표지.shape[0])):
point = 교통안전표지['geometry'].iloc[i]
if data_gid['geometry'].contains(point).sum() == 0:
g1 = "NA"
else :
g = data_gid['gid'].loc[data_gid['geometry'].contains(point)]
g1 = g.iloc[0]
gid_list.append(g1)
교통안전표지['gid'] = gid_list
교통안전표지['safteysign_cnt']=1
result_cnt = 교통안전표지.groupby(['gid']).sum()
result_cnt.reset_index(inplace=True)
교통안전표지 = result_cnt
교통안전표지 = 교통안전표지[['gid', 'safteysign_cnt']]
교통안전표지.to_csv('교통안전표지.csv')
교통CCTV.head()
gid_list = []
for i in tqdm(range(교통CCTV.shape[0])):
point = 교통CCTV['geometry'].iloc[i]
if data_gid['geometry'].contains(point).sum() == 0:
g1 = "NA"
else :
g = data_gid['gid'].loc[data_gid['geometry'].contains(point)]
g1 = g.iloc[0]
gid_list.append(g1)
교통CCTV['gid'] = gid_list
교통CCTV['cctv_cnt']=1
result_cnt = 교통CCTV.groupby(['gid']).sum()
result_cnt.reset_index(inplace=True)
교통CCTV = result_cnt
교통CCTV = 교통CCTV[['gid', 'cctv_cnt']]
교통CCTV.head()
교통CCTV.to_csv('교통CCTV.csv')
중앙분리대 = gpd.read_file("31.대전시_중앙분리대.geojson")
중앙분리대.head()
gid_list = []
for i in tqdm(range(중앙분리대.shape[0])):
point = 중앙분리대['geometry'].iloc[i]
if data_gid['geometry'].contains(point).sum() == 0:
g1 = "NA"
else :
g = data_gid['gid'].loc[data_gid['geometry'].contains(point)]
g1 = g.iloc[0]
gid_list.append(g1)
중앙분리대['gid'] = gid_list
중앙분리대['medianstrip_cnt']=1
result_cnt = 중앙분리대.groupby(['gid']).sum()
result_cnt.reset_index(inplace=True)
중앙분리대 = result_cnt
중앙분리대 = 중앙분리대[['gid', 'medianstrip_cnt']]
중앙분리대.to_csv('중앙분리대.csv')
중앙분리대.head()
차량등록현황.head()
차량등록현황 = 차량등록현황[['gid', 'cars_cnt']]
차량등록현황.to_csv('차량등록현황.csv')
도로명주소_건물.head()
# 격자별로 포함하는 건물(전체 / 주거용 / 시무용) 개수 측정
df1 = 도로명주소_건물.copy()
df2 = df1.loc[:, ['BDTYP_CD','geometry']]
df2['BDTYP_CD'] = [int(x[0:3]) for x in df2.BDTYP_CD] # 건물 용도별로 구분하기 위해 구분열 지정
df2['geometry'] = df2.geometry.centroid # 건물의 중심점으로 geometry 다시 지정
bld = [] # bid는 격자 안에 있는 총 건물의 개수
house = [] # house는 격자 안에 있는 주거용 건물의 개수
office = [] # office는 격자 안에 있는 사무용 건물의 개수
# bid 만들기
temp1 = data_gid.copy()
temp1 = temp1.loc[:, ['gid', 'geometry']]
df3 = df2.copy()
for i in tqdm(range(len(temp1))):
bld.append(sum(df3.geometry.intersects(temp1.geometry[i])))
# house 만들기
df3 = df2.copy()
df3 = df3.loc[(df3['BDTYP_CD']<30),:] # 주거용 건물(건물 용도 번호 앞 세 자리가 30 이하)만 남김
for i in tqdm(range(len(temp1))):
house.append(sum(df3.geometry.intersects(temp1.geometry[i])))
# office 만들기
df3 = df2.copy()
df3 = df3.loc[(df3['BDTYP_CD']==44)|(df3['BDTYP_CD']==100)|(df3['BDTYP_CD']==101)|(df3['BDTYP_CD']==102), :] # 사무용 건물에 해당하는 건물 용도 번호만 남김
for i in tqdm(range(len(temp1))):
office.append(sum(df3.geometry.intersects(temp1.geometry[i])))
# buildings는 기준 데이터와 병합할 데이터
temp1['building'] = bld
temp1['house'] = house
temp1['office'] = office
buildings = temp1.loc[:, ['gid', 'building', 'house', 'office']]
buildings.to_csv('도로명주소_건물.csv')
도로명주소_건물.head()
교통안전표지 = gpd.read_file("9.대전광역시_교통안전표지.geojson")
교통안전표지.head()
b2 = pd.read_excel('29.코드정의서.xlsx')
b2.head()
building_info = pd.merge(도로명주소_건물, b2, left_on='BDTYP_CD',right_on='Unnamed: 0', how='left')[['BDTYP_CD','Unnamed: 1','geometry']]
join = gpd.sjoin(교통사고격자, building_info, how="inner", op="contains")
join
pd.read_csv('16.대전광역시_기상데이터(2017~2019).csv')
df1 = pd.read_csv('차량등록현황.csv')
df2 = pd.read_csv('교통CCTV.csv')
df3 = pd.read_csv('교통안전표지.csv')
df4 = pd.read_csv('도로속도표시.csv')
df5 = pd.read_csv('신호등_보행등.csv')
df6 = pd.read_csv('신호등_차량등.csv')
df7 = pd.read_csv('안전지대.csv')
df8 = pd.read_csv('정차금지지대.csv')
df9 = pd.read_csv('중앙분리대.csv')
df10 = pd.read_csv('횡단보도.csv')
df1 = df1[['gid','cars_cnt']]
df2 = df2[['gid','cctv_cnt']]
df3 = df3[['gid','safteysign_cnt']]
df4 = df4[['gid','speed_cnt']]
df5 = df5[['gid','PTL_cnt']]
df6 = df6[['gid','CTL_cnt']]
df7 = df7[['gid','SafeZone_cnt']]
df8 = df8[['gid','nostop_cnt']]
df9 = df9[['gid','medianstrip_cnt']]
df10 = df10[['gid','Pedcrossing_cnt']]
f1 = pd.merge(df1, df2, on ='gid', how = 'outer')
f1 = pd.merge(f1, df3, on ='gid', how = 'outer')
f1 = pd.merge(f1, df4, on ='gid', how = 'outer')
f1 = pd.merge(f1, df5, on ='gid', how = 'outer')
f1 = pd.merge(f1, df6, on ='gid', how = 'outer')
f1 = pd.merge(f1, df7, on ='gid', how = 'outer')
f1 = pd.merge(f1, df8, on ='gid', how = 'outer')
f1 = pd.merge(f1, df9, on ='gid', how = 'outer')
f1 = pd.merge(f1, df10, on ='gid', how = 'outer')
final_df = f1
# 결측값 0으로 채우기
final_na = f1[f1['gid'] != "Na"]
final_df = final_na.fillna(0)
final_df.head()
# csv 파일 저장
final_df.to_csv('final_data.csv', encoding='utf-8-sig',index=False)
# 격자 데이터 저장
data_gid.to_file('gid_data.geojson', driver= 'GeoJSON')
# geojson 파일로 저장
data_final = pd.merge(final_df, data_gid, on = 'gid', how = 'left')
data_final = gpd.GeoDataFrame(data_final, geometry='geometry')
data_final.head()
data_final.to_file('final_dataset.geojson', driver="GeoJSON",index=False)
data_final = gpd.read_file('final_dataset.geojson')
data_final.sort_values(by='CTL_cnt', ascending=False)
df11 = pd.read_csv('도로명주소_건물.csv')
df11.iloc[:,1:5]
traffic2 = traffic.loc[:, ['가해운전자 차종', '가해운전자 연령대', '가해운전자 성별', '피해운전자 차종', '피해운전자 연령대',
'피해운전자 성별', 'year', '사고', '유형', '동', 'gid', 'geometry']]
traffic2.groupby(['사고'])[['gid']].count()
traffic2.groupby(['유형'])[['gid']].count().sort_values(by='gid', ascending=False)
traffic2.groupby(['사고','유형'])[['gid']].count()
traffic2.groupby(['사고','가해운전자 연령대'])[['gid']].count()
traffic2.loc[traffic2['사고'] == '차대차'].groupby(['gid'])[['사고']].count().sort_values(by='사고', ascending=False)[:100]
traffic2.loc[traffic2['사고'] == '차대차'].groupby(['동','gid'])[['사고']].count().sort_values(by='사고', ascending=False)[:10]
a11 = traffic2.loc[(traffic2['gid'] == '다바882173') | (traffic2['gid'] == '다바883172')
| (traffic2['gid'] == '다바857173') | (traffic2['gid'] == '다바841188')
| (traffic2['gid'] == '다바863171') | (traffic2['gid'] == '다바877178')
| (traffic2['gid'] == '다바882172') | (traffic2['gid'] == '다바941128')
| (traffic2['gid'] == '다바831220') | (traffic2['gid'] == '다바942159') ]
a11.loc[(a11['gid'] == '다바882173') | (a11['gid'] == '다바883172')
| (a11['gid'] == '다바882172')].groupby('유형')[['사고']].count()
a11.loc[a11['gid'] == '다바882172'].groupby('유형')[['사고']].count()
a11.groupby('유형')[['사고']].count()
a11_a = gpd.GeoDataFrame(a11, geometry='geometry')
f1 = np.stack([a11_a['geometry'].centroid.x, a11_a['geometry'].centroid.y], axis=1).reshape([1, -1, 2])
a11_a['사고_경도'] = f1[0,:,0]
a11_a['사고_위도'] = f1[0,:,1]
a11_a['사고_경도'] = a11_a['사고_경도'].astype(float)
a11_a['사고_위도'] = f1[0,:,1].astype(float)
import folium
center = (36.353492, 127.369042); zoom = 15
m = folium.Map(location=center, zoom_start=zoom)
m
## 위치를 지도에서 확인합니다.
import folium
for index, row in a11_a.iterrows():
folium.Marker([row['사고_위도'], row['사고_경도']],
popup=row['gid'],
icon=folium.Icon(color='green', icon_color='white')).add_to(m)
m
data_final_pop.loc[(data_final_pop['gid'] == '다바882173') | (data_final_pop['gid'] == '다바883172')
| (data_final_pop['gid'] == '다바882172')]
x1 = traffic2.loc[traffic2['유형'] == '측면충돌'].groupby('gid')[['사고']].count().sort_values(by='사고', ascending=False)[:100]
pd.set_option('display.max_rows', x1.shape[0]+1)
x1
x2 = traffic2.loc[(traffic2['gid'] == '다바936147') | (traffic2['gid'] == '다바911168')
| (traffic2['gid'] == '다바947170') | (traffic2['gid'] == '다바882173')
| (traffic2['gid'] == '다바892163') | (traffic2['gid'] == '다바941128')
| (traffic2['gid'] == '다바907153') | (traffic2['gid'] == '다바914145')
| (traffic2['gid'] == '다바951164') | (traffic2['gid'] == '다바825181')]
x2
data_final_pop.loc[(data_final_pop['gid'] == '다바936147') | (data_final_pop['gid'] == '다바911168')
| (data_final_pop['gid'] == '다바947170') | (data_final_pop['gid'] == '다바882173')
| (data_final_pop['gid'] == '다바892163') | (data_final_pop['gid'] == '다바941128')
| (data_final_pop['gid'] == '다바907153') | (data_final_pop['gid'] == '다바914145')
| (data_final_pop['gid'] == '다바951164') | (data_final_pop['gid'] == '다바825181')]
x2_a = gpd.GeoDataFrame(x2, geometry='geometry')
f1 = np.stack([x2_a['geometry'].centroid.x, x2_a['geometry'].centroid.y], axis=1).reshape([1, -1, 2])
x2_a['사고_경도'] = f1[0,:,0]
x2_a['사고_위도'] = f1[0,:,1]
for index, row in x2_a.iterrows():
folium.Marker([row['사고_위도'], row['사고_경도']],
popup=row['gid'],
icon=folium.Icon(color='red', icon_color='white')).add_to(m)
m
data_final_pop.loc[(data_final_pop['gid'] == '다바889167') | (data_final_pop['gid'] == '다바898131')
| (data_final_pop['gid'] == '다바943156') | (data_final_pop['gid'] == '다바894178')
| (data_final_pop['gid'] == '다바878174') | (data_final_pop['gid'] == '다바950143')
| (data_final_pop['gid'] == '다바856116') | (data_final_pop['gid'] == '다바891171')
| (data_final_pop['gid'] == '다바904196') | (data_final_pop['gid'] == '다바846172')]
xx2_a = gpd.GeoDataFrame(xx2, geometry='geometry')
f1 = np.stack([xx2_a['geometry'].centroid.x, xx2_a['geometry'].centroid.y], axis=1).reshape([1, -1, 2])
xx2_a['사고_경도'] = f1[0,:,0]
xx2_a['사고_위도'] = f1[0,:,1]
for index, row in xx2_a.iterrows():
folium.Marker([row['사고_위도'], row['사고_경도']],
popup=row['gid'],
icon=folium.Icon(color='blue', icon_color='white')).add_to(m)
m
a1 = data_final_pop.loc[(data_final_pop['gid'] == '다바882173') | (data_final_pop['gid'] == '다바883172')
| (data_final_pop['gid'] == '다바857173') | (data_final_pop['gid'] == '다바841188')
| (data_final_pop['gid'] == '다바863171') | (data_final_pop['gid'] == '다바877178')
| (data_final_pop['gid'] == '다바882172') | (data_final_pop['gid'] == '다바941128')
| (data_final_pop['gid'] == '다바831220') | (data_final_pop['gid'] == '다바942159')]
a2 = 교통사고격자.loc[(교통사고격자['gid'] == '다바882173') | (교통사고격자['gid'] == '다바883172')
| (교통사고격자['gid'] == '다바857173') | (교통사고격자['gid'] == '다바841188')
| (교통사고격자['gid'] == '다바863171') | (교통사고격자['gid'] == '다바877178')
| (교통사고격자['gid'] == '다바882172') | (교통사고격자['gid'] == '다바941128')
| (교통사고격자['gid'] == '다바831220') | (교통사고격자['gid'] == '다바942159')]
aa = pd.merge(a1,a2, on = 'gid')
aa